<!-- 入院检查 一般情况 generalAituation -->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form
        ref="medicalForm"
        :model="formData"
        label-width="160px"
        class="info-form"
        label-position="right"
      >
        <el-divider content-position="left">
          <h3>一般情况</h3>
        </el-divider>

        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>基本信息</span>
          </div>
          <div class="exam-section exam-section-even">
            <el-row :gutter="12">
              <el-col :span="8">
                <!-- 意识状态 -->
                <el-form-item label="意识状态">
                  <div class="display-value info-value">{{ display(formData.consciousness) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 脉搏 -->
                <el-form-item label="脉搏(次/分)">
                  <div class="display-value info-value">{{ display(formData.pulse) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 呼吸 -->
                <el-form-item label="呼吸(次/分)">
                  <div class="display-value info-value">{{ display(formData.respiration) }}</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="8">
                <!-- 血压 -->
                <el-form-item label="血压(mmHg)">
                  <div class="display-value info-value">{{ display(formData.bloodPressure) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 体温 -->
                <el-form-item label="体温(℃)">
                  <div class="display-value info-value">{{ display(formData.bodyTemperature) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 体位 -->
                <el-form-item label="体位">
                  <div class="display-value info-value">{{ display(formData.bodyPosition) }}</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="8">
                <!-- 病容 -->
                <el-form-item label="病容">
                  <div class="display-value info-value">{{ display(formData.sicklyAppearance) }}</div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <!-- 空状态提示 -->
        <el-row v-if="!hasData" :gutter="12" style="margin-top: 16px;">
          <el-col :span="24">
            <el-card class="box-card" shadow="never">
              <div class="empty-state">
                <i class="el-icon-info" style="font-size: 48px; color: #909399; margin-bottom: 16px;" />
                <p style="color: #909399; font-size: 14px;">暂无一般情况数据</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import { general } from '@/api/dataEntry/hospitalAdmissionCheckup'

export default {
  name: 'GeneralAituation',
  data() {
    return {
      formData: {
        id: 0,
        medicalRecordId: 0,
        consciousness: '',
        pulse: null,
        respiration: null,
        bloodPressure: '',
        bodyTemperature: null,
        bodyPosition: '',
        sicklyAppearance: ''
      },
      selectedAppearances: [],
      otherAppearance: ''
    }
  },
  computed: {
    ...mapState('patient', {
      currentPatient: (state) => state.currentPatient
    }),
    ...mapGetters('patient', ['currentPatientId']),
    patientId() {
      return this.currentPatientId || (this.currentPatient && this.currentPatient.id) || null
    },
    // 检查是否有数据
    hasData() {
      return (
        this.formData.consciousness ||
        this.formData.pulse ||
        this.formData.respiration ||
        this.formData.bloodPressure ||
        this.formData.bodyTemperature ||
        this.formData.bodyPosition ||
        this.formData.sicklyAppearance
      )
    }
  },
  watch: {
    currentPatient: {
      handler(newVal) {
        if (newVal) {
          this.loadData(newVal)
          return
        }
        try {
          const raw = localStorage.getItem('CURRENT_PATIENT')
          if (raw) {
            const parsed = JSON.parse(raw)
            if (parsed && Object.keys(parsed).length > 0) {
              this.$store.commit('patient/SET_CURRENT_PATIENT', parsed)
              this.loadData(parsed)
            }
          }
        } catch (e) {
          console.warn('localStorage 读取或解析失败:', e)
        }
      },
      immediate: true,
      deep: true
    },
    currentPatientId: {
      handler(newId) {
        if (newId) {
          this.loadPatientData(newId)
        }
      },
      immediate: true
    },
    selectedAppearances(newVal) {
      this.updateSicklyAppearance()
    },
    otherAppearance(newVal) {
      this.updateSicklyAppearance()
    }
  },
  mounted() {
    if (this.currentPatient && Object.keys(this.currentPatient).length > 0) {
      this.loadData(this.currentPatient)
    } else if (this.patientId) {
      this.loadPatientData(this.patientId)
    }

    if ((!this.currentPatient || Object.keys(this.currentPatient).length === 0) && !this.patientId) {
      try {
        const raw = localStorage.getItem('CURRENT_PATIENT')
        if (raw) {
          const parsed = JSON.parse(raw)
          if (parsed && Object.keys(parsed).length > 0) {
            this.$store.commit('patient/SET_CURRENT_PATIENT', parsed)
            this.loadData(parsed)
          }
        }
      } catch (e) {
        console.warn('mounted: localStorage 读取失败', e)
      }
    }
  },
  methods: {
    loadPatientData(id) {
      general({ recordId: id })
        .then((res) => {
          if (res && res.data) {
            this.loadData(res.data)
          }
        })
        .catch((err) => {
          console.error('加载一般情况数据失败:', err)
        })
    },
    updateSicklyAppearance() {
      let appearances = [...this.selectedAppearances]
      if (this.otherAppearance && this.selectedAppearances.includes('其他')) {
        appearances = appearances.filter((item) => item !== '其他')
        appearances.push(`其他:${this.otherAppearance}`)
      }
      this.formData.sicklyAppearance = appearances.join(',')
    },
    loadData(data) {
      if (data && Object.keys(data).length > 0) {
        this.formData = { ...this.formData, ...data }
        if (data.sicklyAppearance) {
          const appearances = data.sicklyAppearance.split(',')
          this.selectedAppearances = appearances.filter((app) => !app.startsWith('其他:'))
          const otherAppearance = appearances.find((app) => app.startsWith('其他:'))
          if (otherAppearance) {
            this.otherAppearance = otherAppearance.replace('其他:', '')
            this.selectedAppearances.push('其他')
          }
        }
      }
    },
    handleSubmit() {
      this.$refs.medicalForm.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.formData)
        } else {
          this.$message.error('请检查表单填写是否正确')
          return false
        }
      })
    },
    handleReset() {
      this.$refs.medicalForm.resetFields()
      this.selectedAppearances = []
      this.otherAppearance = ''
    },
    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
/* 卡片标题样式增强 */
.box-card >>> .el-card__header {
  background: linear-gradient(135deg, #7b92f9 0%, #8d6de4 100%);
  color: white;
  font-weight: bold;
  padding: 12px 20px;
}
</style>
